import { useEffect, useState, useImperativeHandle } from 'react';
import {
  Button,
  Form,
  Input,
  Select,
  InputNumber,
  Space,
  // Row,
  // Col,
  Typography,
  // message,
  Radio,
} from 'antd';
import { getMessage, TextWidget } from '@inbiz/react';
import { deepClone, getApp } from '@inbiz/utils';
import FormSelect from '@inbiz/basic/FormSelect';
import MultilingualInput from '@inbiz/basic/MultilingualInput';
import { getFormGroupData } from '../servers';
import MemberSelect from './MemberSelect'
import IconPicker from './IconPicker'

const { Option } = Select;
const { Text } = Typography;

// 新建/修改流程弹窗内容组件
const EditModal = (props: any) => {
  // 是否显示图标选择弹窗
  const [visible, $visible] = useState(false)
  // 表单分组数据
  const [formGroupList, $formGroupList] = useState<any>([])
  // 表单
  const [form] = Form.useForm();
  // 关联表单类型
  const formTypes = Form.useWatch('formTypes', form);
  // 关联表单类型
  const pageKey = Form.useWatch('pageKey', form);

  const {
    edit,
    editData,
    submit,
    listData,
    $editModalVisible,
    activeGroupId,
    activeGroupInfo,
    sponsor,
    saveLoading,
    designLoading,
    editRefs,
    disableKeys = [],
  } = props;

  useImperativeHandle(
    editRefs,
    () => ({
      setValue: (val: {
        groupId?: string;
        proLcon?: {
          type: string;
          color: string;
        };
        mark?: string;
        name?: string;
        potentialStarterId?: any;
        pcPageKey?: string;
        pageKey?: string;
        sort?: number;
        descript?: string;
      }) => {
        form.setFieldsValue(val);
      },
      getForm: () => form
    }),
    [form],
  );

  // 初始化
  useEffect(() => {
    requestFormGroupData()
  }, [])

  useEffect(() => {
    if (!editData) {
      form.setFieldsValue({
        groupId: activeGroupId,
        sort: 5,
        formTypes: '1',
      });
    } else {
      // 处理数据进入到成员选择组件反向选中
      let obj = deepClone(editData);
      const types = obj.potentialType?.split(',');
      const identityId = obj.identityId?.split(',');
      obj.potentialStarterId.forEach((item: any, index: any) => {
        item.id = item.key;
        switch (types[index]) {
          case '0':
            item.key = 'user-' + identityId?.[index];
            break;
          case '3':
            item.key = 'group-' + identityId?.[index]
            break;
          case '4':
            item.key = 'position-' + identityId?.[index]
            break;
          case '5':
            item.key = 'department-' + identityId?.[index]
            break;
        }
      })
      // 处理老数据页面选择数据转单纯路由
      if (obj.pcPageKey?.includes?.(',')) {
        obj.pcPageKey = obj.pcPageKey.split(',')?.[1]
      }
      if (obj.pageKey?.includes?.(',')) {
        obj.pageKey = obj.pageKey.split(',')?.[1]
      }
      /* 暂无 */
      obj.formTypes = obj.formTypes ? String(obj.formTypes) : '3'
      // 选择的流程表单时
      if (obj.formTypes == '2') {
        obj.selectForm = obj.association
        obj.pcPageKey = undefined
      }
      form.setFieldsValue(obj);
    }
  }, [editData]);

  // 获取表单分组数据
  const requestFormGroupData = () => {
    getFormGroupData({
      appId: activeGroupInfo?.appId || getApp()?.AppId
    }).then((res: any) => {
      if (Array.isArray(res)) {
        const tree: any[] = res.map((item: any) => {
          return {
            ...item,
            Children: item?.Children?.filter((v: any) => v?.IsGroup)
          }
        })
        const list: any[] = []
        tree.forEach((i: any) => {
          list.push(i)
          if (i.Children?.length) {
            i.Children.forEach((v: any) => {
              list.push({ ...v, down: true, ParentName: i.Name })
            })
          }
        })
        $formGroupList(list)
      } else {
        $formGroupList([])
      }
    })
  }

  return (
    <>
      <div className="edit-process-modal-content">
        <Form
          form={form}
          name="key"
          labelAlign="right"
          colon={false}
          labelCol={{
            span: edit ? 3 : 4,
          }}
          wrapperCol={{
            span: edit ? 21 : 18,
          }}
          autoComplete="off"
        >
          {/* 流程名称 */}
          <Form.Item
            name="name"
            label={getMessage('ProcessManage.process_name')}
            style={{ paddingBottom: 0, minHeight: 54 }}
            required
            rules={[
              ({ }) => ({
                validator(_, value): any {
                  if (!value || value?.trim?.() == '') {
                    return Promise.reject(new Error(getMessage('ProcessManage.name_not_empty')))
                  } else if (!value.includes('{multilingual}global.i18n-') && value.length > 32) {
                    return Promise.reject(getMessage('ProcessManage.name_length_message'))
                  } else if (/^[\u4E00-\u9FA5A-Za-z0-9\_\-\——\'\(\)\。\、\【\】\‘\’\“\”\《\》\……\（\）\s]+$/.test(value)) {
                    // 暂时去掉对语言支持
                    // } else if (/^[\u4E00-\u9FA5A-Za-z0-9\_\-\——\'\(\)\。\、\【\】\‘\’\“\”\《\》\……\（\）\s]+$/.test(value.replace('.i18n', '').replace('{multilingual}', ''))) {
                    return Promise.resolve()
                  }
                  return Promise.reject(getMessage('ProcessManage.special_character'))
                },
              }),
            ]}
          >
            <Input
              placeholder={getMessage('ProcessManage.placeMessage')}
              disabled={disableKeys.includes('name')}
            />
            {/* 暂时去掉对语言支持 */}
            {/* <MultilingualInput
              placeholder={getMessage('ProcessManage.placeMessage')}
              disabled={disableKeys.includes('name')}
            /> */}
          </Form.Item>

          {/* 流程图标 */}
          <Form.Item
            label={
              <Text ellipsis={{ tooltip: getMessage('ProcessManage.process_chart') }}>
                {getMessage('ProcessManage.process_chart')}
              </Text>
            }
            name="proLcon"
            initialValue={{
              type: 'icon-inbiz_process-jiagouliucheng',
              color: 'rgba(170,170,170,1)',
            }}
          >
            <IconPicker visible={visible} onCancel={() => $visible(false)} showIconSize={false} />
          </Form.Item>

          {/* 所属分组 */}
          {props.processName && (
            <Form.Item
              name="groupId"
              label={
                <Text ellipsis={{ tooltip: getMessage('ProcessManage.at_group') }}>
                  {getMessage('ProcessManage.at_group')}
                </Text>
              }
            >
              <Select
                dropdownClassName='process-manage-select-group'
                placeholder={getMessage('ProcessManage.please_sele')} // 请选择
                showSearch
                disabled={disableKeys.includes('groupId')}
                virtual={false}
                optionFilterProp="label"
                filterOption={(input, option) => {
                  if (typeof option?.props?.children == 'string') {
                    return (option?.props?.children ?? '')?.toLowerCase().includes(input.toLowerCase())
                  } else {
                    return false
                  }
                }}
              >
                {
                  listData.map((item: any) => {
                    return (
                      <Select.Option
                        value={item.id}
                        key={item.groupId}
                      >
                        {item.groupName}
                      </Select.Option>
                    )
                  })
                }
              </Select>
            </Form.Item>
          )}

          {/* 流程类型 */}
          {props.processType && (
            <Form.Item
              name="mark"
              label={
                <Text ellipsis={{ tooltip: getMessage('ProcessManage.process_type') }}>
                  {getMessage('ProcessManage.process_type')}
                </Text>
              }
              rules={[{ required: true, message: getMessage('ProcessManage.process_type_message') }]}
              style={{ paddingBottom: 0, minHeight: 54 }}
            >
              {props.defaultOption.length === 0 ? (
                <MultilingualInput disabled={disableKeys.includes('mark')} />
              ) : (
                <Select
                  onChange={(id: string) => {
                    props.emit?.('onSelectGroup', id);
                  }}
                  disabled={disableKeys.includes('mark')}
                >
                  {props.defaultOption.map((item: any) => {
                    return (
                      <Option value={item.groupId} key={item.key} title={getMessage(item.name)}>
                        <TextWidget>{item.name}</TextWidget>
                      </Option>
                    );
                  })}
                </Select>
              )}
            </Form.Item>
          )}

          {/* 关联表单 */}
          <Form.Item
            name='formTypes'
            label={getMessage('ProcessManage.at_form')}
            style={{ paddingBottom: 0, minHeight: 54 }}
            initialValue={'1'}
          >
            <Radio.Group disabled={disableKeys.includes('formTypes') || activeGroupInfo?.appId == '6a04037b4f4511ecb1a60242ac120011'}>
              <Radio value='1'><TextWidget>ProcessManage.add_process</TextWidget></Radio>
              <Radio value='2'><TextWidget>ProcessManage.select_process_form</TextWidget></Radio>
              <Radio value='3'><TextWidget>ProcessManage.custom</TextWidget></Radio>
            </Radio.Group>
          </Form.Item>

          {/* 选择表单分组 */}
          {
            (!formTypes || formTypes == '1') &&
            <Form.Item
              name='selectFormGroup'
              label={
                <Text ellipsis={{ tooltip: getMessage('ProcessManage.form_group') }}>
                  {getMessage('ProcessManage.form_group')}
                </Text>
              }
              rules={[{ required: true, message: getMessage('ProcessManage.form_group_required') }]}
              style={{ paddingBottom: 0, minHeight: 54 }}
            >
              <Select
                dropdownClassName='form-manage-select-group'
                placeholder={getMessage('FormManage.please_sele')} // 请选择
                showSearch
                virtual={false}
                optionFilterProp="label"
                filterOption={(input, option) => {
                  if (typeof option?.title == 'string') {
                    return (option?.title ?? '')?.toLowerCase().includes(input.toLowerCase())
                  } else {
                    return false
                  }
                }}
              >
                {
                  formGroupList.map((item: any) => {
                    return (
                      <Select.Option
                        value={item.OutId}
                        key={item.OutId}
                        className={item.down ? 'form-group-down' : ''}
                        title={getMessage(item.Name)}
                      >
                        <TextWidget>{item.Name}</TextWidget>
                      </Select.Option>
                    )
                  })
                }
              </Select>
            </Form.Item>
          }

          {/* 选择表单 */}
          {
            formTypes == '2' &&
            <Form.Item
              name='selectForm'
              label={getMessage('ProcessManage.select_form')}
              rules={[{ required: true, message: getMessage('ProcessManage.select_form_mess') }]}
              style={{ paddingBottom: 0, minHeight: 54 }}
            >
              <FormSelect appId={activeGroupInfo?.appId} isPublish={false}/>
            </Form.Item>
          }
          {/* PC表单 */}
          {
            formTypes == '3' &&
            <Form.Item
              name='pcPageKey'
              label={getMessage('ProcessManage.pc_form')}
              style={{ paddingBottom: 0, minHeight: 54 }}
              required
              rules={[
                ({ }) => ({
                  validator(_, value): any {
                    if (pageKey && pageKey?.trim?.() != '') {
                      // h5表单有值时只校验pc表单格式不校验非空
                      if (!value || value?.trim?.() == '') {
                        return Promise.resolve()
                      }
                      if (/^(\/|http:\/\/|https:\/\/)/.test(value?.trim())) {
                        return Promise.resolve()
                      }
                      return Promise.reject(getMessage('ProcessManage.pageRule'))
                    } else if (!value || value?.trim?.() == '') { //h5表单无值正常校验
                      return Promise.reject(new Error(getMessage('ProcessManage.pc_form_mess')))
                    } else if (/^(\/|http:\/\/|https:\/\/)/.test(value?.trim())) {
                      return Promise.resolve()
                    }
                    return Promise.reject(getMessage('ProcessManage.pageRule'))
                  },
                }),
              ]}
            >
              <Input placeholder={getMessage('ProcessManage.placeMessage')} disabled={disableKeys.includes('pcForm')} />
            </Form.Item>
          }

          {/* H5表单 */}
          {
            formTypes == '3' &&
            <Form.Item
              name='pageKey'
              label={getMessage('ProcessManage.h5_form')}
              style={{ paddingBottom: 0, minHeight: 54 }}
              rules={[
                ({ }) => ({
                  validator(_, value): any {
                    if (!value || value?.trim?.() == '') {
                      return Promise.resolve()
                    } else if (/^(\/|http:\/\/|https:\/\/)/.test(value?.trim())) {
                      return Promise.resolve()
                    }
                    return Promise.reject(getMessage('ProcessManage.pageRule'))
                  },
                }),
              ]}
            >
              <Input placeholder={getMessage('ProcessManage.placeMessage')} disabled={disableKeys.includes('h5Form')} />
            </Form.Item>
          }

          {/* 发起人 */}
          <Form.Item
            name="potentialStarterId"
            label={getMessage('ProcessManage.people_name')}
            rules={[{ required: true, message: getMessage('ProcessManage.people_name_message') }]}
            style={{ paddingBottom: 0, minHeight: 54 }}
          >
            {sponsor || (
              <MemberSelect
                config={{
                  multiple: true,
                }}
                disabled={disableKeys.includes('potentialStarterId')}
              />
            )}
          </Form.Item>

          {/* 排序 */}
          <Form.Item
            label={
              <Text ellipsis={{ tooltip: getMessage('ProcessManage.sort') }}>
                {getMessage('ProcessManage.sort')}
              </Text>
            }
            name="sort"
          >
            <InputNumber
              min={0}
              style={{ width: '100%' }}
              disabled={disableKeys.includes('sort')}
            />
          </Form.Item>

          {/* 描述 */}
          <Form.Item
            name="descript"
            label={getMessage('ProcessManage.describe')}
            rules={[
              {
                pattern: /^.{1,100}$/,
                message: getMessage('ProcessManage.describe_message'),
              },
            ]}
            style={{ paddingBottom: 0, minHeight: 76 }}
          >
            <Input.TextArea
              autoSize={{ minRows: 2, maxRows: 2 }}
              disabled={disableKeys.includes('descript')}
            />
          </Form.Item>

          {/* 编辑时不渲染按钮，外层抽屉有 */}
          {
            !edit &&
            <Space
              align="end"
              size="middle"
              style={{ padding: '10px 0px 20px 0', width: '100%', justifyContent: 'flex-end' }}
            >
              <Button
                onClick={() => {
                  $editModalVisible(false);
                }}
              >
                <TextWidget>ProcessManage.cancelText</TextWidget>
              </Button>
              <Button type="primary" onClick={() => submit(form, true)} loading={designLoading}>
                <TextWidget>ProcessManage.save_design_text</TextWidget>
              </Button>
              <Button type="primary" onClick={() => submit(form)} loading={saveLoading}>
                <TextWidget>ProcessManage.saveText</TextWidget>
              </Button>
            </Space>
          }
        </Form>
      </div>
    </>
  );
};

export default EditModal;
